package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private CategoryBrandService categoryBrandService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX_CATEGORY = "home:category";

    @Override
    public List<CategoryDTO> queryCategoryByBrandId(Long brandId) {

        //通过baseMapper实现
        //List<Category> categoryList = this.baseMapper.queryCategoryByBrandId(brandId);

        // 1.根据品牌id，查询中间表，得到中间表对象集合
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("brand_id", brandId).list();
        // 2.获取分类id集合
        List<Long> categoryIdList = categoryBrandList.stream()
                .map(CategoryBrand::getCategoryId)
                .collect(Collectors.toList());
        // 3.根据分类id集合，查询分类对象集合
        List<Category> categoryList = this.listByIds(categoryIdList);
        // 4.把PO集合转为DTO集合
        List<CategoryDTO> categoryDTOList = CategoryDTO.convertEntityList(categoryList);
        return categoryDTOList;
    }

    @Override
    public CategoryDTO queryCategoryById(Long id) {
        Category category = this.getById(id);
        // 把PO集合转为DTO
        return new CategoryDTO(category);
    }

    @Override
    public List<CategoryDTO> queryCategoryByIds(List<Long> ids) {
        //mybatis-plus提供的根据id批量查询方法
        List<Category> categoryList = this.listByIds(ids);
        // 把PO集合转为DTO集合
        List<CategoryDTO> categoryDTOList = CategoryDTO.convertEntityList(categoryList);
        return categoryDTOList;
    }

    @Override
    public List<CategoryDTO> queryCategoryByParentId(Long pid) {
        // 根据父类目id查询集合
        List<Category> categoryList = this.query().eq("parent_id", pid).list();
        // 把PO集合转为DTO集合
        List<CategoryDTO> categoryDTOList = CategoryDTO.convertEntityList(categoryList);
        return categoryDTOList;
    }

    @Override
    public List<CategoryDTO> getMenuTree() {
        //1.数据库查询全部菜单数据
        List<Category> categoryList = this.query().list();
        List<CategoryDTO> list = CategoryDTO.convertEntityList(categoryList);
        if (list != null && list.isEmpty() == false) {
            //2.list数据转换到map对象
            Map<Long, CategoryDTO> temp = new HashMap<>();
            list.forEach(menu -> {
                temp.put(menu.getId(), menu);
            });
            //清空list数据,list存放整个树形返回的第一层结构
            list.clear();
            //3.组装树形结构
            for (CategoryDTO menuVO : temp.values()) {
                Long pid = menuVO.getParentId();
                CategoryDTO parent = temp.get(pid);
                if (parent == null) {//没有找到上级节点，说明是根节点
                    list.add(menuVO);
                } else {//找到节点的上级节点，则上级节点的children就添加当前节点进来
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(menuVO);
                }
            }
            return list;
        }
        return null;

    }


    @Override
    public String getIndexMenuTree() {
        //1.数据库查询全部菜单数据
        List<Category> categoryList = this.query().list();
        List<CategoryDTO> list = CategoryDTO.convertEntityList(categoryList);
        if (list != null && list.isEmpty() == false) {
            //2.list数据转换到map对象
            Map<Long, CategoryDTO> temp = new HashMap<>();
            list.forEach(menu -> {
                temp.put(menu.getId(), menu);
            });
            //清空list数据,list存放整个树形返回的第一层结构
            list.clear();
            //3.组装树形结构
            for (CategoryDTO menuVO : temp.values()) {
                Long pid = menuVO.getParentId();
                CategoryDTO parent = temp.get(pid);
                if (parent == null) {//没有找到上级节点，说明是根节点
                    list.add(menuVO);
                } else {//找到节点的上级节点，则上级节点的children就添加当前节点进来
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(menuVO);
                }
            }
            String json = JsonUtils.toJson(list);
            // 存入redis
            redisTemplate.opsForValue().set(KEY_PREFIX_CATEGORY,json,5L, TimeUnit.MINUTES);
            return json;
        }
        return null;

    }
}
